home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / dist-packages / problem_report.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-10-12  |  36.1 KB  |  1,118 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Store, load, and handle problem reports.
  5.  
  6. Copyright (C) 2006 Canonical Ltd.
  7. Author: Martin Pitt <martin.pitt@ubuntu.com>
  8.  
  9. This program is free software; you can redistribute it and/or modify it
  10. under the terms of the GNU General Public License as published by the
  11. Free Software Foundation; either version 2 of the License, or (at your
  12. option) any later version.  See http://www.gnu.org/copyleft/gpl.html for
  13. the full text of the license.
  14. '''
  15. import zlib
  16. import base64
  17. import time
  18. import UserDict
  19. import sys
  20. import gzip
  21. import struct
  22. from cStringIO import StringIO
  23. from email.Encoders import encode_base64
  24. from email.MIMEMultipart import MIMEMultipart
  25. from email.MIMEBase import MIMEBase
  26. from email.MIMEText import MIMEText
  27.  
  28. class CompressedValue:
  29.     '''Represent a ProblemReport value which is gzip compressed.'''
  30.     
  31.     def __init__(self, value = None, name = None):
  32.         '''Initialize an empty CompressedValue object with an optional name.'''
  33.         self.gzipvalue = None
  34.         self.name = name
  35.         self.legacy_zlib = False
  36.         if value:
  37.             self.set_value(value)
  38.         
  39.  
  40.     
  41.     def set_value(self, value):
  42.         '''Set uncompressed value.'''
  43.         out = StringIO()
  44.         gzip.GzipFile(self.name, mode = 'wb', fileobj = out).write(value)
  45.         self.gzipvalue = out.getvalue()
  46.         self.legacy_zlib = False
  47.  
  48.     
  49.     def get_value(self):
  50.         '''Return uncompressed value.'''
  51.         if not self.gzipvalue:
  52.             return None
  53.         if self.legacy_zlib:
  54.             return zlib.decompress(self.gzipvalue)
  55.         return gzip.GzipFile(fileobj = StringIO(self.gzipvalue)).read()
  56.  
  57.     
  58.     def write(self, file):
  59.         '''Write uncompressed value into given file-like object.'''
  60.         if not self.gzipvalue:
  61.             raise AssertionError
  62.         if self.legacy_zlib:
  63.             file.write(zlib.decompress(self.gzipvalue))
  64.             return None
  65.         gz = gzip.GzipFile(fileobj = StringIO(self.gzipvalue))
  66.         while True:
  67.             block = gz.read(1048576)
  68.             file.write(block)
  69.             continue
  70.             None if not block else self.gzipvalue
  71.  
  72.     
  73.     def __len__(self):
  74.         '''Return length of uncompressed value.'''
  75.         if not self.gzipvalue:
  76.             raise AssertionError
  77.         if self.legacy_zlib:
  78.             return len(self.get_value())
  79.         return int(struct.unpack('<L', self.gzipvalue[-4:])[0])
  80.  
  81.     
  82.     def splitlines(self):
  83.         '''Behaves like splitlines() for a normal string.'''
  84.         return self.get_value().splitlines()
  85.  
  86.  
  87.  
  88. class ProblemReport(UserDict.IterableUserDict):
  89.     
  90.     def __init__(self, type = 'Crash', date = None):
  91.         """Initialize a fresh problem report.
  92.  
  93.         type can be 'Crash', 'Packaging', 'KernelCrash' or 'KernelOops'.
  94.         date is the desired date/time string; if None (default), the
  95.         current local time is used. """
  96.         if date == None:
  97.             date = time.asctime()
  98.         
  99.         self.data = {
  100.             'ProblemType': type,
  101.             'Date': date }
  102.         self.old_keys = set()
  103.  
  104.     
  105.     def load(self, file, binary = True):
  106.         """Initialize problem report from a file-like object.
  107.         
  108.         If binary is False, binary data is not loaded; the dictionary key is
  109.         created, but its value will be an empty string. If it is true, it is
  110.         transparently uncompressed and available as dictionary string values.
  111.         If binary is 'compressed', the compressed value is retained, and the
  112.         dictionary value will be a CompressedValue object. This is useful if
  113.         the compressed value is still useful (to avoid recompression if the
  114.         file needs to be written back).
  115.  
  116.         Files are in RFC822 format.
  117.         """
  118.         self.data.clear()
  119.         key = None
  120.         value = None
  121.         b64_block = False
  122.         bd = None
  123.         for line in file:
  124.             if line.startswith(' '):
  125.                 if b64_block and not binary:
  126.                     continue
  127.                 
  128.                 if not key != None or value != None:
  129.                     raise AssertionError
  130.                 if b64_block:
  131.                     l = base64.b64decode(line)
  132.                     if bd:
  133.                         value += bd.decompress(l)
  134.                     elif binary == 'compressed':
  135.                         if value.gzipvalue == '' and not l.startswith('\x1f\x8b\x08'):
  136.                             value.legacy_zlib = True
  137.                         
  138.                         value.gzipvalue += l
  139.                     elif l.startswith('\x1f\x8b\x08'):
  140.                         bd = zlib.decompressobj(-(zlib.MAX_WBITS))
  141.                         value = bd.decompress(self._strip_gzip_header(l))
  142.                     else:
  143.                         bd = zlib.decompressobj()
  144.                         value += bd.decompress(l)
  145.                 elif len(value) > 0:
  146.                     value += '\n'
  147.                 
  148.                 value += line[1:-1]
  149.                 continue
  150.             if b64_block:
  151.                 if bd:
  152.                     value += bd.flush()
  153.                 
  154.                 b64_block = False
  155.                 bd = None
  156.             
  157.             if key:
  158.                 if not value != None:
  159.                     raise AssertionError
  160.                 self.data[key] = value
  161.             
  162.             (key, value) = line.split(':', 1)
  163.             value = value.strip()
  164.             if value == 'base64':
  165.                 if binary == 'compressed':
  166.                     value = CompressedValue(key)
  167.                     value.gzipvalue = ''
  168.                 else:
  169.                     value = ''
  170.                 b64_block = True
  171.                 continue
  172.         
  173.         if key != None:
  174.             self.data[key] = value
  175.         
  176.         self.old_keys = set(self.data.keys())
  177.  
  178.     
  179.     def has_removed_fields(self):
  180.         '''Check whether the report has any keys which were not loaded in load()
  181.         due to being compressed binary.'''
  182.         return '' in self.itervalues()
  183.  
  184.     
  185.     def _is_binary(self, string):
  186.         '''Check if the given strings contains binary data.'''
  187.         for c in string:
  188.             if c < ' ' and not c.isspace():
  189.                 return True
  190.         
  191.         return False
  192.  
  193.     
  194.     def write(self, file, only_new = False):
  195.         """Write information into the given file-like object.
  196.  
  197.         If only_new is True, only keys which have been added since the last
  198.         load() are written (i. e. those returned by new_keys()).
  199.  
  200.         If a value is a string, it is written directly. Otherwise it must be a
  201.         tuple of the form (file, encode=True, limit=None, fail_on_empty=False).
  202.         The first argument can be a file name or a file-like object,
  203.         which will be read and its content will become the value of this key.
  204.         'encode' specifies whether the contents will be
  205.         gzip compressed and base64-encoded (this defaults to True). If limit is
  206.         set to a positive integer, the entire key will be removed. If
  207.         fail_on_empty is True, reading zero bytes will cause an IOError.
  208.  
  209.         Files are written in RFC822 format.
  210.         """
  211.         asckeys = []
  212.         binkeys = []
  213.         for k in self.data.keys():
  214.             if only_new and k in self.old_keys:
  215.                 continue
  216.             
  217.             v = self.data[k]
  218.             if hasattr(v, 'find'):
  219.                 if self._is_binary(v):
  220.                     binkeys.append(k)
  221.                 else:
  222.                     asckeys.append(k)
  223.             self._is_binary(v)
  224.             if not isinstance(v, CompressedValue) and len(v) >= 2 and not v[1]:
  225.                 asckeys.append(k)
  226.                 continue
  227.             binkeys.append(k)
  228.         
  229.         asckeys.sort()
  230.         if 'ProblemType' in asckeys:
  231.             asckeys.remove('ProblemType')
  232.             asckeys.insert(0, 'ProblemType')
  233.         
  234.         binkeys.sort()
  235.         for k in asckeys:
  236.             v = self.data[k]
  237.             if not hasattr(v, 'find'):
  238.                 if len(v) >= 3 and v[2] != None:
  239.                     limit = v[2]
  240.                 else:
  241.                     limit = None
  242.                 if len(v) >= 4:
  243.                     pass
  244.                 fail_on_empty = v[3]
  245.                 if hasattr(v[0], 'read'):
  246.                     v = v[0].read()
  247.                 else:
  248.                     v = open(v[0]).read()
  249.                 if fail_on_empty and len(v) == 0:
  250.                     raise IOError, 'did not get any data for field ' + k
  251.                 len(v) == 0
  252.                 if limit != None and len(v) > limit:
  253.                     del self.data[k]
  254.                     continue
  255.                 
  256.             
  257.             if type(v) == type(u''):
  258.                 v = v.encode('UTF-8')
  259.             
  260.             if '\n' in v:
  261.                 print >>file, k + ':'
  262.                 print >>file, '', v.replace('\n', '\n ')
  263.                 continue
  264.             print >>file, k + ':', v
  265.         
  266.         for k in binkeys:
  267.             v = self.data[k]
  268.             limit = None
  269.             size = 0
  270.             curr_pos = file.tell()
  271.             file.write(k + ': base64\n ')
  272.             if isinstance(v, CompressedValue):
  273.                 file.write(base64.b64encode(v.gzipvalue))
  274.                 file.write('\n')
  275.                 continue
  276.             
  277.             gzip_header = '\x1f\x8b\x08\x08\x00\x00\x00\x00\x02\xff' + k + '\x00'
  278.             file.write(base64.b64encode(gzip_header))
  279.             file.write('\n ')
  280.             crc = zlib.crc32('')
  281.             bc = zlib.compressobj(9, zlib.DEFLATED, -(zlib.MAX_WBITS), zlib.DEF_MEM_LEVEL, 0)
  282.             if hasattr(v, 'find'):
  283.                 size += len(v)
  284.                 crc = zlib.crc32(v, crc)
  285.                 outblock = bc.compress(v)
  286.                 if outblock:
  287.                     file.write(base64.b64encode(outblock))
  288.                     file.write('\n ')
  289.                 
  290.             elif len(v) >= 3 and v[2] != None:
  291.                 limit = v[2]
  292.             
  293.             if hasattr(v[0], 'read'):
  294.                 f = v[0]
  295.             else:
  296.                 f = open(v[0])
  297.             while True:
  298.                 block = f.read(1048576)
  299.                 size += len(block)
  300.                 crc = zlib.crc32(block, crc)
  301.                 if limit != None:
  302.                     if size > limit:
  303.                         file.seek(curr_pos)
  304.                         file.truncate(curr_pos)
  305.                         del self.data[k]
  306.                         crc = None
  307.                         break
  308.                     
  309.                 
  310.                 if block:
  311.                     outblock = bc.compress(block)
  312.                     if outblock:
  313.                         file.write(base64.b64encode(outblock))
  314.                         file.write('\n ')
  315.                     
  316.                 outblock
  317.                 break
  318.             if len(v) >= 4 and v[3]:
  319.                 if size == 0:
  320.                     raise IOError, 'did not get any data for field %s from %s' % (k, str(v[0]))
  321.                 size == 0
  322.             
  323.             if not limit or size <= limit:
  324.                 block = bc.flush()
  325.                 if crc:
  326.                     block += struct.pack('<L', crc & 0xFFFFFFFFL)
  327.                     block += struct.pack('<L', size & 0xFFFFFFFFL)
  328.                 
  329.                 file.write(base64.b64encode(block))
  330.                 file.write('\n')
  331.                 continue
  332.         
  333.  
  334.     
  335.     def add_to_existing(self, reportfile, keep_times = False):
  336.         """Add the fields of this report to an already existing report
  337.         file.
  338.  
  339.         The file will be temporarily chmod'ed to 000 to prevent frontends
  340.         from picking up a hal-updated report file. If keep_times
  341.         is True, then the file's atime and mtime restored after updating."""
  342.         st = os.stat(reportfile)
  343.         
  344.         try:
  345.             f = open(reportfile, 'a')
  346.             os.chmod(reportfile, 0)
  347.             self.write(f)
  348.             f.close()
  349.         finally:
  350.             if keep_times:
  351.                 os.utime(reportfile, (st.st_atime, st.st_mtime))
  352.             
  353.             os.chmod(reportfile, st.st_mode)
  354.  
  355.  
  356.     
  357.     def write_mime(self, file, attach_treshold = 5, extra_headers = { }, skip_keys = None):
  358.         '''Write information into the given file-like object, using
  359.         MIME/Multipart RFC 2822 format (i. e. an email with attachments).
  360.  
  361.         If a value is a string or a CompressedValue, it is written directly.
  362.         Otherwise it must be a tuple containing the source file and an optional
  363.         boolean value (in that order); the first argument can be a file name or
  364.         a file-like object, which will be read and its content will become the
  365.         value of this key.  The file will be gzip compressed, unless the key
  366.         already ends in .gz.
  367.  
  368.         attach_treshold specifies the maximum number of lines for a value to be
  369.         included into the first inline text part. All bigger values (as well as
  370.         all non-ASCII ones) will become an attachment.
  371.  
  372.         Extra MIME preamble headers can be specified, too, as a dictionary.
  373.  
  374.         skip_keys is a set/list specifying keys which are filtered out and not
  375.         written to the destination file.
  376.         '''
  377.         keys = self.data.keys()
  378.         keys.sort()
  379.         text = ''
  380.         attachments = []
  381.         if 'ProblemType' in keys:
  382.             keys.remove('ProblemType')
  383.             keys.insert(0, 'ProblemType')
  384.         
  385.         for k in keys:
  386.             if skip_keys and k in skip_keys:
  387.                 continue
  388.             
  389.             v = self.data[k]
  390.             attach_value = None
  391.             if isinstance(v, CompressedValue):
  392.                 attach_value = v.gzipvalue
  393.             elif not hasattr(v, 'find'):
  394.                 attach_value = ''
  395.                 if hasattr(v[0], 'read'):
  396.                     f = v[0]
  397.                 else:
  398.                     f = open(v[0])
  399.                 if k.endswith('.gz'):
  400.                     attach_value = f.read()
  401.                 else:
  402.                     io = StringIO()
  403.                     gf = gzip.GzipFile(k, mode = 'wb', fileobj = io)
  404.                     while True:
  405.                         block = f.read(1048576)
  406.                         if block:
  407.                             gf.write(block)
  408.                             continue
  409.                         gf.close()
  410.                         break
  411.                     attach_value = io.getvalue()
  412.                 f.close()
  413.             elif self._is_binary(v):
  414.                 if k.endswith('.gz'):
  415.                     attach_value = v
  416.                 else:
  417.                     attach_value = CompressedValue(v, k).gzipvalue
  418.             
  419.             if attach_value:
  420.                 att = MIMEBase('application', 'x-gzip')
  421.                 if k.endswith('.gz'):
  422.                     att.add_header('Content-Disposition', 'attachment', filename = k)
  423.                 else:
  424.                     att.add_header('Content-Disposition', 'attachment', filename = k + '.gz')
  425.                 att.set_payload(attach_value)
  426.                 encode_base64(att)
  427.                 attachments.append(att)
  428.                 continue
  429.             if type(v) == type(u''):
  430.                 v = v.encode('UTF-8')
  431.             
  432.             lines = len(v.splitlines())
  433.             if lines == 1:
  434.                 v = v.rstrip()
  435.                 text += '%s: %s\n' % (k, v)
  436.                 continue
  437.             if lines <= attach_treshold:
  438.                 text += '%s:\n ' % k
  439.                 if not v.endswith('\n'):
  440.                     v += '\n'
  441.                 
  442.                 text += v.strip().replace('\n', '\n ') + '\n'
  443.                 continue
  444.             att = MIMEText(v, _charset = 'UTF-8')
  445.             att.add_header('Content-Disposition', 'attachment', filename = k + '.txt')
  446.             attachments.append(att)
  447.         
  448.         att = MIMEText(text, _charset = 'UTF-8')
  449.         att.add_header('Content-Disposition', 'inline')
  450.         attachments.insert(0, att)
  451.         msg = MIMEMultipart()
  452.         for k, v in extra_headers.iteritems():
  453.             msg.add_header(k, v)
  454.         
  455.         for a in attachments:
  456.             msg.attach(a)
  457.         
  458.         print >>file, msg.as_string()
  459.  
  460.     
  461.     def __setitem__(self, k, v):
  462.         if not hasattr(k, 'isalnum'):
  463.             raise AssertionError
  464.         if not k.replace('.', '').isalnum():
  465.             raise AssertionError
  466.         if not isinstance(v, CompressedValue) and hasattr(v, 'isalnum'):
  467.             if hasattr(v, '__getitem__'):
  468.                 if not (len(v) == 1 or len(v) >= 2 or v[1] in (True, False) or hasattr(v[0], 'isalnum')) and hasattr(v[0], 'read'):
  469.                     raise AssertionError
  470.                 return self.data.__setitem__(k, v)
  471.  
  472.     
  473.     def new_keys(self):
  474.         '''Return the set of keys which have been added to the report since it
  475.         was constructed or loaded.'''
  476.         return set(self.data.keys()) - self.old_keys
  477.  
  478.     
  479.     def _strip_gzip_header(klass, line):
  480.         '''Strip gzip header from line and return the rest.'''
  481.         flags = ord(line[3])
  482.         offset = 10
  483.         if flags & 4:
  484.             offset += line[offset] + 1
  485.         
  486.         if flags & 8:
  487.             while ord(line[offset]) != 0:
  488.                 offset += 1
  489.             offset += 1
  490.         
  491.         if flags & 16:
  492.             while ord(line[offset]) != 0:
  493.                 offset += 1
  494.             offset += 1
  495.         
  496.         if flags & 2:
  497.             offset += 2
  498.         
  499.         return line[offset:]
  500.  
  501.     _strip_gzip_header = classmethod(_strip_gzip_header)
  502.  
  503. import unittest
  504. import tempfile
  505. import os
  506. import email
  507.  
  508. class _ProblemReportTest(unittest.TestCase):
  509.     
  510.     def test_basic_operations(self):
  511.         '''basic creation and operation.'''
  512.         pr = ProblemReport()
  513.         pr['foo'] = 'bar'
  514.         pr['bar'] = ' foo   bar\nbaz\n   blip  '
  515.         self.assertEqual(pr['foo'], 'bar')
  516.         self.assertEqual(pr['bar'], ' foo   bar\nbaz\n   blip  ')
  517.         self.assertEqual(pr['ProblemType'], 'Crash')
  518.         self.assert_(time.strptime(pr['Date']))
  519.  
  520.     
  521.     def test_ctor_arguments(self):
  522.         '''non-default constructor arguments.'''
  523.         pr = ProblemReport('KernelCrash')
  524.         self.assertEqual(pr['ProblemType'], 'KernelCrash')
  525.         pr = ProblemReport(date = '19801224 12:34')
  526.         self.assertEqual(pr['Date'], '19801224 12:34')
  527.  
  528.     
  529.     def test_sanity_checks(self):
  530.         '''various error conditions.'''
  531.         pr = ProblemReport()
  532.         self.assertRaises(AssertionError, pr.__setitem__, 'a b', '1')
  533.         self.assertRaises(AssertionError, pr.__setitem__, 'a', 1)
  534.         self.assertRaises(AssertionError, pr.__setitem__, 'a', 1)
  535.         self.assertRaises(AssertionError, pr.__setitem__, 'a', (1,))
  536.         self.assertRaises(AssertionError, pr.__setitem__, 'a', ('/tmp/nonexistant', ''))
  537.         self.assertRaises(KeyError, pr.__getitem__, 'Nonexistant')
  538.  
  539.     
  540.     def test_compressed_values(self):
  541.         '''handling of CompressedValue values.'''
  542.         large_val = 'A' * 5000000
  543.         pr = ProblemReport()
  544.         pr['Foo'] = CompressedValue('FooFoo!')
  545.         pr['Bin'] = CompressedValue()
  546.         pr['Bin'].set_value('ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z')
  547.         pr['Large'] = CompressedValue(large_val)
  548.         self.assert_(isinstance(pr['Foo'], CompressedValue))
  549.         self.assert_(isinstance(pr['Bin'], CompressedValue))
  550.         self.assertEqual(pr['Foo'].get_value(), 'FooFoo!')
  551.         self.assertEqual(pr['Bin'].get_value(), 'ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z')
  552.         self.assertEqual(pr['Large'].get_value(), large_val)
  553.         self.assertEqual(len(pr['Foo']), 7)
  554.         self.assertEqual(len(pr['Bin']), 31)
  555.         self.assertEqual(len(pr['Large']), len(large_val))
  556.         io = StringIO()
  557.         pr['Bin'].write(io)
  558.         self.assertEqual(io.getvalue(), 'ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z')
  559.         io = StringIO()
  560.         pr['Large'].write(io)
  561.         self.assertEqual(io.getvalue(), large_val)
  562.         pr['Multiline'] = CompressedValue('\x01\x01\x01\n\x02\x02\n\x03\x03\x03')
  563.         self.assertEqual(pr['Multiline'].splitlines(), [
  564.             '\x01\x01\x01',
  565.             '\x02\x02',
  566.             '\x03\x03\x03'])
  567.         io = StringIO()
  568.         pr.write(io)
  569.         io.seek(0)
  570.         pr = ProblemReport()
  571.         pr.load(io)
  572.         self.assertEqual(pr['Foo'], 'FooFoo!')
  573.         self.assertEqual(pr['Bin'], 'ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z')
  574.         self.assertEqual(pr['Large'], large_val)
  575.  
  576.     
  577.     def test_write(self):
  578.         '''write() and proper formatting.'''
  579.         pr = ProblemReport(date = 'now!')
  580.         pr['Simple'] = 'bar'
  581.         pr['SimpleUTF8'] = '1\xc3\xa4\xc3\xb62\xce\xa63'
  582.         pr['SimpleUnicode'] = u'1√§√∂2Œ¶3'
  583.         pr['TwoLineUTF8'] = 'pi-\xcf\x80\nnu-\xce\xb7'
  584.         pr['TwoLineUnicode'] = u'pi-œÄ\nnu-Œ∑'
  585.         pr['WhiteSpace'] = ' foo   bar\nbaz\n  blip  \n\nafteremptyline'
  586.         io = StringIO()
  587.         pr.write(io)
  588.         self.assertEqual(io.getvalue(), 'ProblemType: Crash\nDate: now!\nSimple: bar\nSimpleUTF8: 1\xc3\xa4\xc3\xb62\xce\xa63\nSimpleUnicode: 1\xc3\xa4\xc3\xb62\xce\xa63\nTwoLineUTF8:\n pi-\xcf\x80\n nu-\xce\xb7\nTwoLineUnicode:\n pi-\xcf\x80\n nu-\xce\xb7\nWhiteSpace:\n  foo   bar\n baz\n   blip  \n \n afteremptyline\n')
  589.  
  590.     
  591.     def test_write_append(self):
  592.         '''write() with appending to an existing file.'''
  593.         pr = ProblemReport(date = 'now!')
  594.         pr['Simple'] = 'bar'
  595.         pr['WhiteSpace'] = ' foo   bar\nbaz\n  blip  '
  596.         io = StringIO()
  597.         pr.write(io)
  598.         pr.clear()
  599.         pr['Extra'] = 'appended'
  600.         pr.write(io)
  601.         self.assertEqual(io.getvalue(), 'ProblemType: Crash\nDate: now!\nSimple: bar\nWhiteSpace:\n  foo   bar\n baz\n   blip  \nExtra: appended\n')
  602.         temp = tempfile.NamedTemporaryFile()
  603.         temp.write('ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z')
  604.         temp.flush()
  605.         pr = ProblemReport(date = 'now!')
  606.         pr['File'] = (temp.name,)
  607.         io = StringIO()
  608.         pr.write(io)
  609.         temp.close()
  610.         pr.clear()
  611.         pr['Extra'] = 'appended'
  612.         pr.write(io)
  613.         io.seek(0)
  614.         pr = ProblemReport()
  615.         pr.load(io)
  616.         self.assertEqual(pr['Date'], 'now!')
  617.         self.assertEqual(pr['File'], 'ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z')
  618.         self.assertEqual(pr['Extra'], 'appended')
  619.  
  620.     
  621.     def test_load(self):
  622.         '''load() with various formatting.'''
  623.         pr = ProblemReport()
  624.         pr.load(StringIO('ProblemType: Crash\nDate: now!\nSimple: bar\nWhiteSpace:\n  foo   bar\n baz\n   blip  \n'))
  625.         self.assertEqual(pr['ProblemType'], 'Crash')
  626.         self.assertEqual(pr['Date'], 'now!')
  627.         self.assertEqual(pr['Simple'], 'bar')
  628.         self.assertEqual(pr['WhiteSpace'], ' foo   bar\nbaz\n  blip  ')
  629.         pr.load(StringIO('ProblemType: Crash\nDate: now!\nSimple: bar\nWhiteSpace:\n  foo   bar\n baz\n   blip  \n \n'))
  630.         self.assertEqual(pr['ProblemType'], 'Crash')
  631.         self.assertEqual(pr['Date'], 'now!')
  632.         self.assertEqual(pr['Simple'], 'bar')
  633.         self.assertEqual(pr['WhiteSpace'], ' foo   bar\nbaz\n  blip  \n')
  634.         pr = ProblemReport()
  635.         pr.load(StringIO('ProblemType: Crash\nWhiteSpace:\n  foo   bar\n baz\n \n   blip  \nLast: foo\n'))
  636.         self.assertEqual(pr['WhiteSpace'], ' foo   bar\nbaz\n\n  blip  ')
  637.         self.assertEqual(pr['Last'], 'foo')
  638.         pr.load(StringIO('ProblemType: Crash\nWhiteSpace:\n  foo   bar\n baz\n   blip  \nLast: foo\n \n'))
  639.         self.assertEqual(pr['WhiteSpace'], ' foo   bar\nbaz\n  blip  ')
  640.         self.assertEqual(pr['Last'], 'foo\n')
  641.         invalid_spacing = StringIO('WhiteSpace:\n first\n\n second\n')
  642.         pr = ProblemReport()
  643.         self.assertRaises(ValueError, pr.load, invalid_spacing)
  644.         pr.load(StringIO('ProblemType: Crash'))
  645.         self.assertEqual(pr.keys(), [
  646.             'ProblemType'])
  647.  
  648.     
  649.     def test_write_file(self):
  650.         '''writing a report with binary file data.'''
  651.         temp = tempfile.NamedTemporaryFile()
  652.         temp.write('ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z')
  653.         temp.flush()
  654.         pr = ProblemReport(date = 'now!')
  655.         pr['File'] = (temp.name,)
  656.         pr['Afile'] = (temp.name,)
  657.         io = StringIO()
  658.         pr.write(io)
  659.         temp.close()
  660.         self.assertEqual(io.getvalue(), 'ProblemType: Crash\nDate: now!\nAfile: base64\n H4sICAAAAAAC/0FmaWxlAA==\n c3RyxIAMcBAFAK/2p9MfAAAA\nFile: base64\n H4sICAAAAAAC/0ZpbGUA\n c3RyxIAMcBAFAK/2p9MfAAAA\n')
  661.         temp = tempfile.NamedTemporaryFile()
  662.         temp.write('foo\x00bar')
  663.         temp.flush()
  664.         pr = ProblemReport(date = 'now!')
  665.         pr['File'] = (temp.name, False)
  666.         io = StringIO()
  667.         pr.write(io)
  668.         self.assertEqual(io.getvalue(), 'ProblemType: Crash\nDate: now!\nFile: foo\x00bar\n')
  669.         pr['File'] = (temp.name, True)
  670.         io = StringIO()
  671.         pr.write(io)
  672.         self.assertEqual(io.getvalue(), 'ProblemType: Crash\nDate: now!\nFile: base64\n H4sICAAAAAAC/0ZpbGUA\n S8vPZ0hKLAIACq50HgcAAAA=\n')
  673.         temp.close()
  674.  
  675.     
  676.     def test_write_fileobj(self):
  677.         '''writing a report with a pointer to a file-like object.'''
  678.         tempbin = StringIO('ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z')
  679.         tempasc = StringIO('Hello World')
  680.         pr = ProblemReport(date = 'now!')
  681.         pr['BinFile'] = (tempbin,)
  682.         pr['AscFile'] = (tempasc, False)
  683.         io = StringIO()
  684.         pr.write(io)
  685.         io.seek(0)
  686.         pr = ProblemReport()
  687.         pr.load(io)
  688.         self.assertEqual(pr['BinFile'], tempbin.getvalue())
  689.         self.assertEqual(pr['AscFile'], tempasc.getvalue())
  690.  
  691.     
  692.     def test_write_empty_fileobj(self):
  693.         '''writing a report with a pointer to a file-like object with enforcing non-emptyness.'''
  694.         tempbin = StringIO('')
  695.         tempasc = StringIO('')
  696.         pr = ProblemReport(date = 'now!')
  697.         pr['BinFile'] = (tempbin, True, None, True)
  698.         io = StringIO()
  699.         self.assertRaises(IOError, pr.write, io)
  700.         pr = ProblemReport(date = 'now!')
  701.         pr['AscFile'] = (tempasc, False, None, True)
  702.         io = StringIO()
  703.         self.assertRaises(IOError, pr.write, io)
  704.  
  705.     
  706.     def test_write_delayed_fileobj(self):
  707.         '''writing a report with file pointers and delayed data.'''
  708.         (fout, fin) = os.pipe()
  709.         if os.fork() == 0:
  710.             os.close(fout)
  711.             time.sleep(0.3)
  712.             os.write(fin, 'ab' * 512 * 1024)
  713.             time.sleep(0.3)
  714.             os.write(fin, 'hello')
  715.             time.sleep(0.3)
  716.             os.write(fin, ' world')
  717.             os.close(fin)
  718.             os._exit(0)
  719.         
  720.         os.close(fin)
  721.         pr = ProblemReport(date = 'now!')
  722.         pr['BinFile'] = (os.fdopen(fout),)
  723.         io = StringIO()
  724.         pr.write(io)
  725.         if not os.wait()[1] == 0:
  726.             raise AssertionError
  727.         io.seek(0)
  728.         pr2 = ProblemReport()
  729.         pr2.load(io)
  730.         self.assert_(pr2['BinFile'].endswith('abhello world'))
  731.         self.assertEqual(len(pr2['BinFile']), 1048576 + len('hello world'))
  732.  
  733.     
  734.     def test_read_file(self):
  735.         '''reading a report with binary data.'''
  736.         bin_report = 'ProblemType: Crash\nDate: now!\nFile: base64\n H4sICAAAAAAC/0ZpbGUA\n c3RyxIAMcBAFAK/2p9MfAAAA\nFoo: Bar\n'
  737.         pr = ProblemReport()
  738.         pr.load(StringIO(bin_report))
  739.         self.assertEqual(pr['File'], 'ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z')
  740.         self.assertEqual(pr.has_removed_fields(), False)
  741.         pr.load(StringIO(bin_report), binary = False)
  742.         self.assertEqual(pr['File'], '')
  743.         self.assertEqual(pr.has_removed_fields(), True)
  744.         pr.load(StringIO(bin_report), binary = 'compressed')
  745.         self.assertEqual(pr['Foo'], 'Bar')
  746.         self.assertEqual(pr.has_removed_fields(), False)
  747.         self.assert_(isinstance(pr['File'], CompressedValue))
  748.         self.assertEqual(pr['File'].get_value(), 'ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z')
  749.  
  750.     
  751.     def test_read_file_legacy(self):
  752.         '''reading a report with binary data in legacy format without gzip
  753.         header.'''
  754.         bin_report = 'ProblemType: Crash\nDate: now!\nFile: base64\n eJw=\n c3RyxIAMcBAFAG55BXk=\nFoo: Bar\n'
  755.         data = 'ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z'
  756.         pr = ProblemReport()
  757.         pr.load(StringIO(bin_report))
  758.         self.assertEqual(pr['File'], data)
  759.         self.assertEqual(pr.has_removed_fields(), False)
  760.         pr.load(StringIO(bin_report), binary = False)
  761.         self.assertEqual(pr['File'], '')
  762.         self.assertEqual(pr.has_removed_fields(), True)
  763.         pr.load(StringIO(bin_report), binary = 'compressed')
  764.         self.assertEqual(pr.has_removed_fields(), False)
  765.         self.assertEqual(len(pr['File']), len(data))
  766.         self.assertEqual(pr['File'].get_value(), data)
  767.         io = StringIO()
  768.         pr['File'].write(io)
  769.         io.seek(0)
  770.         self.assertEqual(io.read(), data)
  771.  
  772.     
  773.     def test_big_file(self):
  774.         '''writing and re-decoding a big random file.'''
  775.         temp = tempfile.NamedTemporaryFile()
  776.         data = os.urandom(1048576)
  777.         temp.write(data)
  778.         temp.flush()
  779.         pr = ProblemReport()
  780.         pr['File'] = (temp.name,)
  781.         pr['Before'] = 'xtestx'
  782.         pr['ZAfter'] = 'ytesty'
  783.         io = StringIO()
  784.         pr.write(io)
  785.         temp.close()
  786.         io.seek(0)
  787.         pr = ProblemReport()
  788.         pr.load(io)
  789.         self.assert_(pr['File'] == data)
  790.         self.assertEqual(pr['Before'], 'xtestx')
  791.         self.assertEqual(pr['ZAfter'], 'ytesty')
  792.         io2 = StringIO()
  793.         pr.write(io2)
  794.         self.assert_(io.getvalue() == io2.getvalue())
  795.         io.seek(0)
  796.         pr = ProblemReport()
  797.         pr.load(io, binary = 'compressed')
  798.         self.assertEqual(pr['File'].get_value(), data)
  799.  
  800.     
  801.     def test_size_limit(self):
  802.         '''writing and a big random file with a size limit key.'''
  803.         temp = tempfile.NamedTemporaryFile()
  804.         data = os.urandom(1048576)
  805.         temp.write(data)
  806.         temp.flush()
  807.         pr = ProblemReport()
  808.         pr['FileSmallLimit'] = (temp.name, True, 100)
  809.         pr['FileLimitMinus1'] = (temp.name, True, 1048575)
  810.         pr['FileExactLimit'] = (temp.name, True, 1048576)
  811.         pr['FileLimitPlus1'] = (temp.name, True, 1048577)
  812.         pr['FileLimitNone'] = (temp.name, True, None)
  813.         pr['Before'] = 'xtestx'
  814.         pr['ZAfter'] = 'ytesty'
  815.         io = StringIO()
  816.         pr.write(io)
  817.         temp.close()
  818.         io.seek(0)
  819.         pr = ProblemReport()
  820.         pr.load(io)
  821.         self.failIf(pr.has_key('FileSmallLimit'))
  822.         self.failIf(pr.has_key('FileLimitMinus1'))
  823.         self.assert_(pr['FileExactLimit'] == data)
  824.         self.assert_(pr['FileLimitPlus1'] == data)
  825.         self.assert_(pr['FileLimitNone'] == data)
  826.         self.assertEqual(pr['Before'], 'xtestx')
  827.         self.assertEqual(pr['ZAfter'], 'ytesty')
  828.  
  829.     
  830.     def test_iter(self):
  831.         '''ProblemReport iteration.'''
  832.         pr = ProblemReport()
  833.         pr['foo'] = 'bar'
  834.         keys = []
  835.         for k in pr:
  836.             keys.append(k)
  837.         
  838.         keys.sort()
  839.         self.assertEqual(' '.join(keys), 'Date ProblemType foo')
  840.         []([](_[1]), 2)
  841.  
  842.     
  843.     def test_modify(self):
  844.         '''reading, modifying fields, and writing back.'''
  845.         report = 'ProblemType: Crash\nDate: now!\nLong:\n xxx\n .\n yyy\nShort: Bar\nFile: base64\n H4sICAAAAAAC/0ZpbGUA\n c3RyxIAMcBAFAK/2p9MfAAAA\n'
  846.         pr = ProblemReport()
  847.         pr.load(StringIO(report))
  848.         self.assertEqual(pr['Long'], 'xxx\n.\nyyy')
  849.         io = StringIO()
  850.         pr.write(io)
  851.         self.assertEqual(io.getvalue(), report)
  852.         pr['Short'] = 'aaa\nbbb'
  853.         pr['Long'] = '123'
  854.         io = StringIO()
  855.         pr.write(io)
  856.         self.assertEqual(io.getvalue(), 'ProblemType: Crash\nDate: now!\nLong: 123\nShort:\n aaa\n bbb\nFile: base64\n H4sICAAAAAAC/0ZpbGUA\n c3RyxIAMcBAFAK/2p9MfAAAA\n')
  857.  
  858.     
  859.     def test_add_to_existing(self):
  860.         '''adding information to an existing report.'''
  861.         pr = ProblemReport()
  862.         pr['old1'] = '11'
  863.         pr['old2'] = '22'
  864.         (fd, rep) = tempfile.mkstemp()
  865.         os.close(fd)
  866.         pr.write(open(rep, 'w'))
  867.         origstat = os.stat(rep)
  868.         pr = ProblemReport()
  869.         pr.clear()
  870.         pr['new1'] = '33'
  871.         pr.add_to_existing(rep, keep_times = True)
  872.         newstat = os.stat(rep)
  873.         self.assertEqual(origstat.st_mode, newstat.st_mode)
  874.         self.assertAlmostEqual(origstat.st_atime, newstat.st_atime, 1)
  875.         self.assertAlmostEqual(origstat.st_mtime, newstat.st_mtime, 1)
  876.         newpr = ProblemReport()
  877.         newpr.load(open(rep))
  878.         self.assertEqual(newpr['old1'], '11')
  879.         self.assertEqual(newpr['old2'], '22')
  880.         self.assertEqual(newpr['new1'], '33')
  881.         time.sleep(1)
  882.         open(rep).read()
  883.         time.sleep(1)
  884.         pr = ProblemReport()
  885.         pr.clear()
  886.         pr['new2'] = '44'
  887.         pr.add_to_existing(rep)
  888.         newstat = os.stat(rep)
  889.         self.assertEqual(origstat.st_mode, newstat.st_mode)
  890.         self.assertNotEqual(origstat.st_mtime, newstat.st_mtime)
  891.         skip_atime = False
  892.         dir = rep
  893.         while len(dir) > 1:
  894.             (dir, filename) = os.path.split(dir)
  895.             if os.path.ismount(dir):
  896.                 for line in open('/proc/mounts'):
  897.                     (mount, fs, options) = line.split(' ')[1:4]
  898.                     if mount == dir and 'noatime' in options.split(','):
  899.                         skip_atime = True
  900.                         break
  901.                         continue
  902.                 
  903.                 break
  904.                 continue
  905.         if not skip_atime:
  906.             self.assertNotEqual(origstat.st_atime, newstat.st_atime)
  907.         
  908.         newpr = ProblemReport()
  909.         newpr.load(open(rep))
  910.         self.assertEqual(newpr['old1'], '11')
  911.         self.assertEqual(newpr['old2'], '22')
  912.         self.assertEqual(newpr['new1'], '33')
  913.         self.assertEqual(newpr['new2'], '44')
  914.         os.unlink(rep)
  915.  
  916.     
  917.     def test_write_mime_text(self):
  918.         '''write_mime() for text values.'''
  919.         pr = ProblemReport(date = 'now!')
  920.         pr['Simple'] = 'bar'
  921.         pr['SimpleUTF8'] = '1\xc3\xa4\xc3\xb62\xce\xa63'
  922.         pr['SimpleUnicode'] = u'1√§√∂2Œ¶3'
  923.         pr['SimpleLineEnd'] = 'bar\n'
  924.         pr['TwoLine'] = 'first\nsecond\n'
  925.         pr['TwoLineUTF8'] = 'pi-\xcf\x80\nnu-\xce\xb7\n'
  926.         pr['TwoLineUnicode'] = u'pi-œÄ\nnu-Œ∑\n'
  927.         pr['InlineMargin'] = 'first\nsecond\nthird\nfourth\nfifth\n'
  928.         pr['Multiline'] = ' foo   bar\nbaz\n  blip  \nline4\nline\xe2\x99\xa55!!\n\xc5\x82\xc4\xb1\xc2\xb5\xe2\x82\xac \xe2\x85\x9d\n'
  929.         io = StringIO()
  930.         pr.write_mime(io)
  931.         io.seek(0)
  932.         msg = email.message_from_file(io)
  933.         msg_iter = msg.walk()
  934.         part = msg_iter.next()
  935.         self.assert_(part.is_multipart())
  936.         part = msg_iter.next()
  937.         self.assert_(not part.is_multipart())
  938.         self.assertEqual(part.get_content_type(), 'text/plain')
  939.         self.assertEqual(part.get_content_charset(), 'utf-8')
  940.         self.assertEqual(part.get_filename(), None)
  941.         self.assertEqual(part.get_payload(decode = True), 'ProblemType: Crash\nDate: now!\nInlineMargin:\n first\n second\n third\n fourth\n fifth\nSimple: bar\nSimpleLineEnd: bar\nSimpleUTF8: 1\xc3\xa4\xc3\xb62\xce\xa63\nSimpleUnicode: 1\xc3\xa4\xc3\xb62\xce\xa63\nTwoLine:\n first\n second\nTwoLineUTF8:\n pi-\xcf\x80\n nu-\xce\xb7\nTwoLineUnicode:\n pi-\xcf\x80\n nu-\xce\xb7\n')
  942.         part = msg_iter.next()
  943.         self.assert_(not part.is_multipart())
  944.         self.assertEqual(part.get_content_type(), 'text/plain')
  945.         self.assertEqual(part.get_content_charset(), 'utf-8')
  946.         self.assertEqual(part.get_filename(), 'Multiline.txt')
  947.         self.assertEqual(part.get_payload(decode = True), ' foo   bar\nbaz\n  blip  \nline4\nline\xe2\x99\xa55!!\n\xc5\x82\xc4\xb1\xc2\xb5\xe2\x82\xac \xe2\x85\x9d\n')
  948.         self.assertRaises(StopIteration, msg_iter.next)
  949.  
  950.     
  951.     def test_write_mime_binary(self):
  952.         '''write_mime() for binary values and file references.'''
  953.         bin_value = 'ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z'
  954.         temp = tempfile.NamedTemporaryFile()
  955.         temp.write(bin_value)
  956.         temp.flush()
  957.         tempgz = tempfile.NamedTemporaryFile()
  958.         gz = gzip.GzipFile('File1', 'w', fileobj = tempgz)
  959.         gz.write(bin_value)
  960.         gz.close()
  961.         tempgz.flush()
  962.         pr = ProblemReport(date = 'now!')
  963.         pr['Context'] = 'Test suite'
  964.         pr['File1'] = (temp.name,)
  965.         pr['File1.gz'] = (tempgz.name,)
  966.         pr['Value1'] = bin_value
  967.         pr['Value1.gz'] = open(tempgz.name).read()
  968.         pr['ZValue'] = CompressedValue(bin_value)
  969.         io = StringIO()
  970.         pr.write_mime(io)
  971.         io.seek(0)
  972.         msg = email.message_from_file(io)
  973.         msg_iter = msg.walk()
  974.         part = msg_iter.next()
  975.         self.assert_(part.is_multipart())
  976.         part = msg_iter.next()
  977.         self.assert_(not part.is_multipart())
  978.         self.assertEqual(part.get_content_type(), 'text/plain')
  979.         self.assertEqual(part.get_content_charset(), 'utf-8')
  980.         self.assertEqual(part.get_filename(), None)
  981.         self.assertEqual(part.get_payload(decode = True), 'ProblemType: Crash\nContext: Test suite\nDate: now!\n')
  982.         part = msg_iter.next()
  983.         self.assert_(not part.is_multipart())
  984.         self.assertEqual(part.get_content_type(), 'application/x-gzip')
  985.         self.assertEqual(part.get_filename(), 'File1.gz')
  986.         f = tempfile.TemporaryFile()
  987.         f.write(part.get_payload(decode = True))
  988.         f.seek(0)
  989.         self.assertEqual(gzip.GzipFile(mode = 'rb', fileobj = f).read(), bin_value)
  990.         part = msg_iter.next()
  991.         self.assert_(not part.is_multipart())
  992.         self.assertEqual(part.get_content_type(), 'application/x-gzip')
  993.         self.assertEqual(part.get_filename(), 'File1.gz')
  994.         f = tempfile.TemporaryFile()
  995.         f.write(part.get_payload(decode = True))
  996.         f.seek(0)
  997.         self.assertEqual(gzip.GzipFile(mode = 'rb', fileobj = f).read(), bin_value)
  998.         part = msg_iter.next()
  999.         self.assert_(not part.is_multipart())
  1000.         self.assertEqual(part.get_content_type(), 'application/x-gzip')
  1001.         self.assertEqual(part.get_filename(), 'Value1.gz')
  1002.         f = tempfile.TemporaryFile()
  1003.         f.write(part.get_payload(decode = True))
  1004.         f.seek(0)
  1005.         self.assertEqual(gzip.GzipFile(mode = 'rb', fileobj = f).read(), bin_value)
  1006.         part = msg_iter.next()
  1007.         self.assert_(not part.is_multipart())
  1008.         self.assertEqual(part.get_content_type(), 'application/x-gzip')
  1009.         self.assertEqual(part.get_filename(), 'Value1.gz')
  1010.         f = tempfile.TemporaryFile()
  1011.         f.write(part.get_payload(decode = True))
  1012.         f.seek(0)
  1013.         self.assertEqual(gzip.GzipFile(mode = 'rb', fileobj = f).read(), bin_value)
  1014.         part = msg_iter.next()
  1015.         self.assert_(not part.is_multipart())
  1016.         self.assertEqual(part.get_content_type(), 'application/x-gzip')
  1017.         self.assertEqual(part.get_filename(), 'ZValue.gz')
  1018.         f = tempfile.TemporaryFile()
  1019.         f.write(part.get_payload(decode = True))
  1020.         f.seek(0)
  1021.         self.assertEqual(gzip.GzipFile(mode = 'rb', fileobj = f).read(), bin_value)
  1022.         self.assertRaises(StopIteration, msg_iter.next)
  1023.  
  1024.     
  1025.     def test_write_mime_extra_headers(self):
  1026.         '''write_mime() with extra headers.'''
  1027.         pr = ProblemReport(date = 'now!')
  1028.         pr['Simple'] = 'bar'
  1029.         pr['TwoLine'] = 'first\nsecond\n'
  1030.         io = StringIO()
  1031.         pr.write_mime(io, extra_headers = {
  1032.             'Greeting': 'hello world',
  1033.             'Foo': 'Bar' })
  1034.         io.seek(0)
  1035.         msg = email.message_from_file(io)
  1036.         self.assertEqual(msg['Greeting'], 'hello world')
  1037.         self.assertEqual(msg['Foo'], 'Bar')
  1038.         msg_iter = msg.walk()
  1039.         part = msg_iter.next()
  1040.         self.assert_(part.is_multipart())
  1041.         part = msg_iter.next()
  1042.         self.assert_(not part.is_multipart())
  1043.         self.assertEqual(part.get_content_type(), 'text/plain')
  1044.         self.assert_('Simple: bar' in part.get_payload(decode = True))
  1045.         self.assertRaises(StopIteration, msg_iter.next)
  1046.  
  1047.     
  1048.     def test_write_mime_filter(self):
  1049.         '''write_mime() with key filters.'''
  1050.         bin_value = 'ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z'
  1051.         pr = ProblemReport(date = 'now!')
  1052.         pr['GoodText'] = 'Hi'
  1053.         pr['BadText'] = 'YouDontSeeMe'
  1054.         pr['GoodBin'] = bin_value
  1055.         pr['BadBin'] = 'Y' + '\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05' + '-'
  1056.         io = StringIO()
  1057.         pr.write_mime(io, skip_keys = [
  1058.             'BadText',
  1059.             'BadBin'])
  1060.         io.seek(0)
  1061.         msg = email.message_from_file(io)
  1062.         msg_iter = msg.walk()
  1063.         part = msg_iter.next()
  1064.         self.assert_(part.is_multipart())
  1065.         part = msg_iter.next()
  1066.         self.assert_(not part.is_multipart())
  1067.         self.assertEqual(part.get_content_type(), 'text/plain')
  1068.         self.assertEqual(part.get_content_charset(), 'utf-8')
  1069.         self.assertEqual(part.get_filename(), None)
  1070.         self.assertEqual(part.get_payload(decode = True), 'ProblemType: Crash\nDate: now!\nGoodText: Hi\n')
  1071.         part = msg_iter.next()
  1072.         self.assert_(not part.is_multipart())
  1073.         f = tempfile.TemporaryFile()
  1074.         f.write(part.get_payload(decode = True))
  1075.         f.seek(0)
  1076.         self.assertEqual(gzip.GzipFile(mode = 'rb', fileobj = f).read(), bin_value)
  1077.         self.assertRaises(StopIteration, msg_iter.next)
  1078.  
  1079.     
  1080.     def test_updating(self):
  1081.         '''new_keys() and write() with only_new=True.'''
  1082.         pr = ProblemReport()
  1083.         self.assertEqual(pr.new_keys(), set([
  1084.             'ProblemType',
  1085.             'Date']))
  1086.         pr.load(StringIO('ProblemType: Crash\nDate: now!\nFoo: bar\nBaz: blob\n'))
  1087.         self.assertEqual(pr.new_keys(), set())
  1088.         pr['Foo'] = 'changed'
  1089.         pr['NewKey'] = 'new new'
  1090.         self.assertEqual(pr.new_keys(), set([
  1091.             'NewKey']))
  1092.         out = StringIO()
  1093.         pr.write(out, only_new = True)
  1094.         self.assertEqual(out.getvalue(), 'NewKey: new new\n')
  1095.  
  1096.     
  1097.     def test_import_dict(self):
  1098.         '''importing a dictionary with update().'''
  1099.         pr = ProblemReport()
  1100.         pr['oldtext'] = 'Hello world'
  1101.         pr['oldbin'] = 'ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z'
  1102.         pr['overwrite'] = 'I am crap'
  1103.         d = { }
  1104.         d['newtext'] = 'Goodbye world'
  1105.         d['newbin'] = '11\x00\x01\x02\xffZZ'
  1106.         d['overwrite'] = 'I am good'
  1107.         pr.update(d)
  1108.         self.assertEqual(pr['oldtext'], 'Hello world')
  1109.         self.assertEqual(pr['oldbin'], 'ABABABABABABABABABAB' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 'Z')
  1110.         self.assertEqual(pr['newtext'], 'Goodbye world')
  1111.         self.assertEqual(pr['newbin'], '11\x00\x01\x02\xffZZ')
  1112.         self.assertEqual(pr['overwrite'], 'I am good')
  1113.  
  1114.  
  1115. if __name__ == '__main__':
  1116.     unittest.main()
  1117.  
  1118.